#define _CRT_SECURE_NO_WARNINGS
class LRUCache {
public:
    struct Node
    {
        Node() :key(0), val(0), prev(nullptr), next(nullptr)
        {}
        Node(int _key, int _val) :key(_key), val(_val), prev(nullptr), next(nullptr)
        {}
        int key, val;
        Node* prev, * next;
    };
    LRUCache(int capacity) :_capacity(capacity), _size(0)
    {
        head = new Node();
        tail = new Node();
        head->next = tail;
        tail->prev = head;
    }

    int get(int key) {
        if (!hash.count(key))  return -1;
        Node* node = hash[key];
        removeNode(node);
        addNodeToHead(node);
        return node->val;
    }

    void put(int key, int value) {
        if (hash.count(key))
        {
            Node* node = hash[key];
            removeNode(node);
            addNodeToHead(node);
            node->val = value;
        }
        else
        {
            Node* node = new Node(key, value);
            addNodeToHead(node);
            hash[key] = node;
            if (++_size > _capacity)
            {
                Node* remove = tail->prev;
                removeNode(remove);
                hash.erase(remove->key);
                delete remove;
            }
        }
    }

    void removeNode(Node* node)
    {
        Node* prev = node->prev;
        Node* next = node->next;
        prev->next = next;
        next->prev = prev;
    }
    void addNodeToHead(Node* node)
    {
        Node* headNext = head->next;
        head->next = node;
        node->prev = head;
        node->next = headNext;
        headNext->prev = node;
    }

private:
    unordered_map<int, Node*> hash;
    Node* head, * tail;
    size_t _size;
    size_t _capacity;
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */